import requests
import time
from pymongo import MongoClient
from fake_useragent import UserAgent
import json

# 建立数据库
client = MongoClient()  # 新建数据库实例
db = client.group  # 新建group数据库
pro = db.Season_data_pg  # 新建Season_data_pg表格

groups = ['clippers','lakers','kings','warriors','suns','grizzlies','pelicans','mavericks','rockets','spurs',
         'jazz','nuggets','thunder','timberwolves','blazers','sixers','celtics','knicks','nets','raptors',
         'hornets','hawks','heat','magic','wizards','bucks','bulls','cavaliers','pacers','pistons']

def get_Season_data_pg():
    for group in groups:
        ua = UserAgent()
        url = 'http://china.nba.com/static/data/team/stats_' + group + '.json'
        # 请求头
        headers={}
        headers['User-Agent'] = ua.random
        # 获取数据
        r = requests.get(url,headers = headers)
        # 打印payload和seasons中的数据
        data = r.json()['payload']['seasons']
        print(type(data))
        # print(r.json()['payload']['seasons'])
        设置文件名
        filename = group + '队各年赛季数据.json'
        # 写入文件
        with open(filename,'w') as f:
            json.dump(data, f)

        print('球队：' + group + '获取成功')
        # if r.status_code == 200:

        pro.insert(data)
        # else:
        # print("错误！")
        print("获取成功，正在保存球队：" + group + "到数据库！")
        time.sleep(1)

if __name__ == '__main__':
    get_Season_data_pg()



